/**
 * @author Jonathan Jung, Timothy Hong, Ronen Adam
 * 
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;

public class RxEngine extends Thread {
    private RouterEngine routerEngine;
    private DatagramSocket socket;
    private boolean running;

    public RxEngine(DatagramSocket ds, RouterEngine engine) {
        routerEngine = engine;
        socket = ds;
        running = false;
        this.setName("rx " + this.getId());
    }

    public void run() {
        running = true;
        while (running == true) {
            try {
                receive();
            } catch (InstantiationException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    private void receive() throws InstantiationException, IOException {
        byte[] buffer = new byte[1526];
        DatagramPacket receivedPacket = new DatagramPacket(buffer,
                buffer.length);

        EthernetFrame receivedMessage = null;

        while (true) {
            System.out.println("********" + this.getName()
                    + " is Recieving********");
            socket.receive(receivedPacket);

            // Extract data from receivedPacket and truncate excess padding
            byte[] data = receivedPacket.getData();
            byte[] frame = new byte[receivedPacket.getLength()];
            System.arraycopy(data, 0, frame, 0, frame.length);

            receivedMessage = new EthernetFrame(frame);

            // :TODO This has not been tested. Hoping that this will connect
            // router engine with receiver. Whenever the rx gets something, it
            // will add to the queue in the routger engine
            routerEngine.getReceivedQ().add(receivedMessage);

            // Ethernet information for testing
            System.out.println("Ethernet Frame to be recieved:\n"
                    + receivedMessage.toString());
            System.out.println(new String(receivedMessage.getFramePayload()));

        }

    }

    public void halt() {
        running = false;
    }

}